9.6 HTTP Middleware

Source: Internet
Author: User

 PackageMainImport("IO"    "Log"    "Net/http")typeUserstringfunc(U User) toString ()string{return string(U)}typeAuthhandlerfunc(U User, w http.) Responsewriter, R *http. Request)funcMain () {//Secured APIMUX: = http. Newservemux () Mux. Handlefunc ("/api/users", Secure (func(W http. Responsewriter, R *http. Request) {io. WriteString (W,' [{' id ': ' 1 ', ' Login ': ' Ffghi '},{' id ': ' 2 ', ' Login ': ' FFGHJ '}] ')) Mux. Handlefunc ("/api/profile", Withuser (func(U User, w http.) Responsewriter, R *http. Request) {log. Println (u.tostring ()) Io. WriteString (W,"{\"User\":\""+u.tostring () +"\"}")}) http. Listenandserve (": 8080", MUX)}funcWithuser (H authhandler) http. Handlerfunc {return func(W http. Responsewriter, R *http. Request) {User: = R.header.get ("X-user")if Len(user) = =0{W.writeheader (http. statusunauthorized)return} h (User, W, r)}}funcSecure (H http. Handlerfunc) http. Handlerfunc {return func(W http. Responsewriter, R *http. Request) {sec: = R.header.get ("X-auth")ifSec! ="Authenticated"{W.writeheader (http. statusunauthorized)return} h (W, R)// Use the handler}}/*(sx3.5.3)? ~ Curl-x get-i http://127.0.0.1:8080/api/usershttp/1.1 401 UnauthorizedDate:mon, 2018 15:42:50 GMTcontent-length:0Content-type:text/plain; Charset=utf-8curl-x get-w "\nstatus:%{http_code}\n" Http://127.0.0.1:8080/api/usersstatus:401curl-x get-w "\nstatus:%{http_code}\n" Http://127.0.0.1:8080/api/users-H "x-auth:authenticated "[{"id": "1", "Login": "Ffghi"},{"id": "2", "Login": "Ffghj"}]status:200(sx3.5.3)? ~ Curl-x get-w "\nstatus:%{http_code}\n" Http://127.0.0.1:8080/api/profile-H "X-user:zrd "{"User": "Zrd"}status:200*/
在前面的例子中中间件的实现利用函数为一等公民的Golang特色。原handlerfunc包装成一个handlerfunc检查x-auth头。安全功能是用来保护handlerfunc,用于servemux的handlefunc方法。请注意,这只是一个简单的示例,但这种方式可以实现更复杂的解决方案。例如,用户的身份可以从标题标记和随后的提取,处理新类型可以定义为类AuthHandler func(U *用户,W http.responsewriter,R * HTTP请求)。功能的用户创建的servemux的handlerfunc。

9.6 HTTP Middleware

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.