golang 设置web请求状态码操作
来源:脚本之家
2022-12-23 18:25:18
0浏览
收藏
对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《golang 设置web请求状态码操作》,主要介绍了web请求、状态码,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!
我就废话不多说了,大家还是直接看代码吧~
package main
import (
"net/http"
)
func main() {
//路由处理绑定
http.HandleFunc("/", Hander)
//监听8080端口
http.ListenAndServe(":8080", nil)
}
func Hander(w http.ResponseWriter, req *http.Request) {
//设置 http请求状态
w.WriteHeader(500)
//写入页面数据
w.Write([]byte("xiaochuan"))
}
你也可以用http 包里面的常量 我这边直接写数字方便理解而已
const ( StatusContinue = 100 StatusSwitchingProtocols = 101 StatusOK = 200 StatusCreated = 201 StatusAccepted = 202 StatusNonAuthoritativeInfo = 203 StatusNoContent = 204 StatusResetContent = 205 StatusPartialContent = 206 StatusMultipleChoices = 300 StatusMovedPermanently = 301 StatusFound = 302 StatusSeeOther = 303 StatusNotModified = 304 StatusUseProxy = 305 StatusTemporaryRedirect = 307 StatusBadRequest = 400 StatusUnauthorized = 401 StatusPaymentRequired = 402 StatusForbidden = 403 StatusNotFound = 404 StatusMethodNotAllowed = 405 StatusNotAcceptable = 406 StatusProxyAuthRequired = 407 StatusRequestTimeout = 408 StatusConflict = 409 StatusGone = 410 StatusLengthRequired = 411 StatusPreconditionFailed = 412 StatusRequestEntityTooLarge = 413 StatusRequestURITooLong = 414 StatusUnsupportedMediaType = 415 StatusRequestedRangeNotSatisfiable = 416 StatusExpectationFailed = 417 StatusTeapot = 418 StatusInternalServerError = 500 StatusNotImplemented = 501 StatusBadGateway = 502 StatusServiceUnavailable = 503 StatusGatewayTimeout = 504 StatusHTTPVersionNotSupported = 505 // New HTTP status codes from RFC 6585. Not exported yet in Go 1.1. // See discussion at https://codereview.appspot.com/7678043/ statusPreconditionRequired = 428 statusTooManyRequests = 429 statusRequestHeaderFieldsTooLarge = 431 statusNetworkAuthenticationRequired = 511 )
下面修改一下就是这个样子
package main
import (
"net/http"
)
func main() {
//路由处理绑定
http.HandleFunc("/", Hander)
//监听8080端口
http.ListenAndServe(":8080", nil)
}
func Hander(w http.ResponseWriter, req *http.Request) {
//设置 http请求状态 为500
w.WriteHeader(http.StatusInternalServerError)
//写入页面数据
w.Write([]byte("xiaochuan"))
}
补充:go status.go 状态码定义
status.go使用了一个map集合定义了http的响应状态码
具体的参考如下
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package http
// HTTP status codes, defined in RFC 2616.
const (
StatusContinue = 100
StatusSwitchingProtocols = 101
StatusOK = 200
StatusCreated = 201
StatusAccepted = 202
StatusNonAuthoritativeInfo = 203
StatusNoContent = 204
StatusResetContent = 205
StatusPartialContent = 206
StatusMultipleChoices = 300
StatusMovedPermanently = 301
StatusFound = 302
StatusSeeOther = 303
StatusNotModified = 304
StatusUseProxy = 305
StatusTemporaryRedirect = 307
StatusBadRequest = 400
StatusUnauthorized = 401
StatusPaymentRequired = 402
StatusForbidden = 403
StatusNotFound = 404
StatusMethodNotAllowed = 405
StatusNotAcceptable = 406
StatusProxyAuthRequired = 407
StatusRequestTimeout = 408
StatusConflict = 409
StatusGone = 410
StatusLengthRequired = 411
StatusPreconditionFailed = 412
StatusRequestEntityTooLarge = 413
StatusRequestURITooLong = 414
StatusUnsupportedMediaType = 415
StatusRequestedRangeNotSatisfiable = 416
StatusExpectationFailed = 417
StatusTeapot = 418
StatusPreconditionRequired = 428
StatusTooManyRequests = 429
StatusRequestHeaderFieldsTooLarge = 431
StatusUnavailableForLegalReasons = 451
StatusInternalServerError = 500
StatusNotImplemented = 501
StatusBadGateway = 502
StatusServiceUnavailable = 503
StatusGatewayTimeout = 504
StatusHTTPVersionNotSupported = 505
StatusNetworkAuthenticationRequired = 511
)
var statusText = map[int]string{
StatusContinue: "Continue",
StatusSwitchingProtocols: "Switching Protocols",
StatusOK: "OK",
StatusCreated: "Created",
StatusAccepted: "Accepted",
StatusNonAuthoritativeInfo: "Non-Authoritative Information",
StatusNoContent: "No Content",
StatusResetContent: "Reset Content",
StatusPartialContent: "Partial Content",
StatusMultipleChoices: "Multiple Choices",
StatusMovedPermanently: "Moved Permanently",
StatusFound: "Found",
StatusSeeOther: "See Other",
StatusNotModified: "Not Modified",
StatusUseProxy: "Use Proxy",
StatusTemporaryRedirect: "Temporary Redirect",
StatusBadRequest: "Bad Request",
StatusUnauthorized: "Unauthorized",
StatusPaymentRequired: "Payment Required",
StatusForbidden: "Forbidden",
StatusNotFound: "Not Found",
StatusMethodNotAllowed: "Method Not Allowed",
StatusNotAcceptable: "Not Acceptable",
StatusProxyAuthRequired: "Proxy Authentication Required",
StatusRequestTimeout: "Request Timeout",
StatusConflict: "Conflict",
StatusGone: "Gone",
StatusLengthRequired: "Length Required",
StatusPreconditionFailed: "Precondition Failed",
StatusRequestEntityTooLarge: "Request Entity Too Large",
StatusRequestURITooLong: "Request URI Too Long",
StatusUnsupportedMediaType: "Unsupported Media Type",
StatusRequestedRangeNotSatisfiable: "Requested Range Not Satisfiable",
StatusExpectationFailed: "Expectation Failed",
StatusTeapot: "I'm a teapot",
StatusPreconditionRequired: "Precondition Required",
StatusTooManyRequests: "Too Many Requests",
StatusRequestHeaderFieldsTooLarge: "Request Header Fields Too Large",
StatusUnavailableForLegalReasons: "Unavailable For Legal Reasons",
StatusInternalServerError: "Internal Server Error",
StatusNotImplemented: "Not Implemented",
StatusBadGateway: "Bad Gateway",
StatusServiceUnavailable: "Service Unavailable",
StatusGatewayTimeout: "Gateway Timeout",
StatusHTTPVersionNotSupported: "HTTP Version Not Supported",
StatusNetworkAuthenticationRequired: "Network Authentication Required",
}
// 返回httpcode对应的 状态码描述信息
// 返回空字符串表示状态码 unknown
func StatusText(code int) string {
return statusText[code]
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持golang学习网。如有错误或未考虑完全的地方,望不吝赐教。
到这里,我们也就讲完了《golang 设置web请求状态码操作》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于golang的知识点!
版本声明
本文转载于:脚本之家 如有侵犯,请联系study_golang@163.com删除
golang网络通信超时设置方式
- 上一篇
- golang网络通信超时设置方式
- 下一篇
- golang API开发过程的中的自动重启方式(基于gin框架)
评论列表
-
- 强健的芹菜
- 这篇文章出现的刚刚好,细节满满,写的不错,mark,关注作者大大了!希望作者大大能多写Golang相关的文章。
- 2023-02-13 14:56:38
-
- 俏皮的飞鸟
- 好细啊,收藏了,感谢老哥的这篇文章,我会继续支持!
- 2023-02-10 22:52:12
-
- 大力的柚子
- 这篇技术文章太及时了,细节满满,感谢大佬分享,码住,关注师傅了!希望师傅能多写Golang相关的文章。
- 2023-01-21 12:06:00
-
- 动人的小懒猪
- 很棒,一直没懂这个问题,但其实工作中常常有遇到...不过今天到这,看完之后很有帮助,总算是懂了,感谢作者分享技术文章!
- 2022-12-31 11:10:43
-
- 大力的大白
- 真优秀,一直没懂这个问题,但其实工作中常常有遇到...不过今天到这,帮助很大,总算是懂了,感谢大佬分享博文!
- 2022-12-28 18:51:27
查看更多
最新文章
-
- Golang · Go教程 | 11分钟前 |
- Go 模板里访问嵌套字段失败时怎么定位字段路径
- 486浏览 收藏
-
- Golang · Go教程 | 22分钟前 |
- Go 模板执行后输出空字符串怎么区分零值和缺失字段
- 204浏览 收藏
-
- Golang · Go教程 | 35分钟前 |
- Go text/template 缺少 map 键时怎么让它直接报错
- 102浏览 收藏
-
- Golang · Go教程 | 48分钟前 | 正则表达式 · Go教程 · 日志解析 · Go regexp 日志解析 SubexpIndex FindStringSubmatch
- Go 正则匹配日志字段时怎么把子匹配映射成结构体
- 436浏览 收藏
-
- Golang · Go教程 | 59分钟前 | 错误排查 · 字符串匹配 · Go正则表达式 · Go regexp 命名捕获组 FindStringSubmatch
- Go 正则 FindStringSubmatch 返回空切片时怎么判断原因
- 207浏览 收藏
-
- Golang · Go教程 | 1小时前 | go · 正则表达式 · regexp · 字符串解析 · Go regexp 命名捕获组 SubexpIndex SubexpNames
- Go regexp 怎么用命名捕获组解析可选字段
- 252浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- Go URL 拼接时怎么避免双斜杠和转义重复
- 149浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- Go net/url 怎么只编码查询参数而不破坏路径斜杠
- 347浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- Go errors.As 提取自定义错误时怎么保留操作上下文
- 227浏览 收藏
-
- Golang · Go教程 | 2小时前 | 标准库 · 错误处理 · go · Go 错误包装 errors.Is errors.Join
- Go errors.Is 判断包装错误时怎么避免误判同类错误
- 325浏览 收藏
-
- Golang · Go教程 | 2小时前 | 标准库 · 错误处理 · go · 表单校验 errors.Is Go错误处理 errors.Join
- Go errors.Join 怎么保留多个校验错误并让调用方逐个判断
- 214浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- SuperCLUE
- SuperCLUE是权威的中文大语言模型综合评测基准,涵盖语言理解、知识应用、AI Agent智能体及安全性等12项核心能力。通过多轮对话与客观测试,定期发布榜单与技术报告,为模型研发、优化及行业选型提供科学依据。
- 173次使用
-
- C-Eval
- 深入了解C-Eval中文评估套件,涵盖52个学科与4级难度。本文详解其功能特点、Zero-shot/Few-shot使用方法及代码示例,助您全面评测LLM中文理解与泛化能力。
- 106次使用
-
- AI Prompt Library
- 探索AI Prompt Library免费资源库,涵盖营销、写作及多场景AI提示词。兼容ChatGPT、Claude等工具,一键复制优化输出,提升工作效率。
- 34次使用
-
- LangGPT
- LangGPT是一种受编程语言启发的结构化提示词设计工具,提供双层框架、模块化模板及变量功能,帮助用户高效编写高质量Prompt。该项目已在GitHub免费开源,适用于内容创作、编程辅助等多场景。
- 42次使用
-
- ClickPrompt
- ClickPrompt是一款专为AI提示词编写者设计的开源在线工具,支持Stable Diffusion绘图、ChatGPT对话及GitHub Copilot代码辅助。提供Prompt自动生成、一键运行、社区分享及可视化优化功能,帮助用户高效获取精准AI输出。
- 79次使用
查看更多
相关文章
-
- Java 性能优化上线清单:从定位、改造到灰度发布
- 2026-06-11 860浏览
-
- Spring Boot 压测验证:Gatling、JMeter 与性能回归门禁
- 2026-06-11 843浏览
-
- Java NMT 非堆内存排查:Direct Buffer、线程栈与 Metaspace 分析
- 2026-06-11 826浏览
-
- Spring Boot 容器内存优化:JVM 堆、非堆与 MaxRAMPercentage
- 2026-06-11 809浏览
-
- Tomcat 连接与线程参数调优:maxThreads、acceptCount 与 KeepAlive
- 2026-06-11 792浏览

