golang 设置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]
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。如有错误或未考虑完全的地方,望不吝赐教。

(0)

相关推荐

  • golang websocket 服务端的实现

    创建一个websocket的服务端 package smile import ( "errors" "log" "net/http" "sync" "time" "github.com/gorilla/websocket" ) const ( // 允许等待的写入时间 writeWait = 10 * time.Second // Time allowed to read the nex

  • Gin golang web开发模型绑定实现过程解析

    我们了解到gin可用通过类似DefaultQuery或DefaultPostForm等方法获取到前端提交过来的参数.参数不多的情况下也很好用,但是想想看,如果接口有很多个参数的时候再用这种方法就要调用很多次获取参数的方法,本文将介绍一种新的接收参数的方法来解决这个问题:模型绑定. gin中的模型绑定可以理解为:把请求的参数映射为一个具体的类型.gin支持JSON,XML,YAML和表单参数等多种参数格式,只需要在对应的字段上声明标签. 绑定表单或者查询字符串 type Person struct

  • Golang实现web文件共享服务的示例代码

    本文主要介绍了Golang实现web文件共享服务的示例代码,分享给大家,具体如下: 很简单,只需要两行代码. http.Handle("/", http.FileServer(http.Dir("./"))) //把当前文件目录作为共享目录 http.ListenAndServe(":8080", nil) 这时候,通过浏览器打开 http://ip 地址:8080 就可以了. 也许这样就完了,但是我为了方便非程序员用户使用,还需要程序自动获取本

  • 基于gin的golang web开发:路由示例详解

    Gin是一个用Golang编写的HTTP网络框架.它的特点是类似于Martini的API,性能更好.在golang web开发领域是一个非常热门的web框架. 启动一个Gin web服务器 使用下面的命令安装Gin go get -u github.com/gin-gonic/gin 在代码里添加依赖 import "github.com/gin-gonic/gin" 快速启动一个Gin服务器的代码如下 package main import "github.com/gin-

  • 基于gin的golang web开发之认证利器jwt

    JSON Web Token(JWT)是一种很流行的跨域认证解决方案,JWT基于JSON可以在进行验证的同时附带身份信息,对于前后端分离项目很有帮助. eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c JWT由三部分组成,每个部分之间用点

  • golang 设置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请求状态

  • python中使用urllib2获取http请求状态码的代码例子

    采集内容常需要得到网页返回的验证码做进一步处理 下面代码是用python写的用来获取网页http状态码的脚本 #!/usr/bin/python # -*- coding: utf-8 -*- #encoding=utf-8 #Filename:states_code.py import urllib2 url = 'http://www.jb51.net/' response = None try: response = urllib2.urlopen(url,timeout=5) excep

  • Java Web请求与响应实例详解

    Servlet最主要作用就是处理客户端请求并作出回应,为此,针对每次请求,Web容器在调用service()之前都会创建两个对象,分别是HttpServletRequest和HttpServletResponse.其中HttpServletRequest封装HTTP请求消息,HttpServletResponse封装HTTP响应消息.需要注意的是,Web服务器运行过程中,每个Servlet都会只创建一个实例对象,不过每次请求都会调用Servlet实例的service(ServletRequest

  • Tomcat源码解析之Web请求与处理

    前言 Tomcat最全UML类图 Tomcat请求处理过程: Connector对象创建的时候,会创建Http11NioProtocol的ProtocolHandler,在Connector的startInteral方法中,会启动AbstractProtocol,AbstractProtocol启动NioEndPoint进行监听客户端的请求,EndPoint接受到客户端的请求之后,会交给Container去处理请求.请求从Engine开始经过的所有容器都含有责任链模式,每经过一个容器都会调用该容

  • java发送http请求并获取状态码的简单实例

    目前做项目中有一个需求是这样的,需要通过java发送url请求,查看该url是否有效,这时我们可以通过获取状态码来判断. try { URL u = new URL("http://10.1.2.8:8080/fqz/page/qizha/pros_add.jsp"); try { HttpURLConnection uConnection = (HttpURLConnection) u.openConnection(); try { uConnection.connect(); Sy

  • IOS HTTP请求的常见状态码总结

    IOS HTTP请求的常见状态码总结 1xx消息 这一类型的状态码,代表请求已被接受,需要继续处理.这类响应是临时响应,只包含状态行和某些可选的响应头信息,并以空行结束.由于HTTP/1.0协议中没有定义任何1xx状态码,所以除非在某些试验条件下,服务器禁止向此类客户端发送1xx响应. 这些状态码代表的响应都是信息性的,标示客户应该采取的其他行动. 100 Continue 客户端应当继续发送请求.这个临时响应是用来通知客户端它的部分请求已经被服务器接收,且仍未被拒绝.客户端应当继续发送请求的剩

  • RestTemplate设置超时时间及返回状态码非200处理

    目录 1.调试postForEntity请求 2.设置超时时间 默认情况下使用RestTemplate如果返回结果的状态码是200的话就正常处理,否则都会抛出异常: 1.调试postForEntity请求 调试postForEntity请求的方法找到判断响应结果状态码的方法是org.springframework.web.client.DefaultResponseErrorHandler类中的hasError方法 @Override public boolean hasError(Client

  • GoLang channel关闭状态相关操作详解

    关于 channel 的使用,有几点不方便的地方: 1.在不改变 channel 自身状态的情况下,无法获知一个 channel 是否关闭. 2.关闭一个 closed channel 会导致 panic.所以,如果关闭 channel 的一方在不知道 channel 是否处于关闭状态时就去贸然关闭 channel 是很危险的事情. 3.向一个 closed channel 发送数据会导致 panic.所以,如果向 channel 发送数据的一方不知道 channel 是否处于关闭状态时就去贸然

  • 快速解决ajax请求出错状态码为0的问题

    今天在使用 ajax 向后台请求数据时出现错误,提示状态码为 0 ,后台采用的是 spring mvc 架构. 状态码为0是什么意思呢?查找了下,原来它意味着 (未初始化)即没有调用到send()方法,我原来代码如下 : $.ajax({ url:"test", type:"post", data:{ blogTitle : $("#form1 input").val(), blogType : $("#form1 option:sel

  • 微信小程序设置全局请求URL及封装wx.request请求操作示例

    本文实例讲述了微信小程序设置全局请求URL及封装wx.request请求操作.分享给大家供大家参考,具体如下: app.js: App({ //设置全局请求URL globalData:{ URL: 'https://www.oyhdo.com', }, /** * 封装wx.request请求 * method: 请求方式 * url: 请求地址 * data: 要传递的参数 * callback: 请求成功回调函数 * errFun: 请求失败回调函数 **/ wxRequest(metho

随机推荐