美文网首页
第15章 15.5-健壮的http应用

第15章 15.5-健壮的http应用

作者: yezide | 来源:发表于2020-01-25 14:57 被阅读0次
package main

import (
    "io"
    "log"
    "net/http"
)

const form = `<html><body><form action="#" method="post" name="bar">
        <input type="text" name="in"/>
        <input type="submit" value="Submit"/>
    </form></html></body>`

type MyHandleFunc func(http.ResponseWriter, *http.Request)

// 最简单的输出html
func SimpleServer(w http.ResponseWriter, req *http.Request) {
    io.WriteString(w, "<h1>hello go</h1>")
}

// 首先是GET方式,显示html表单
// 点submit之后变成了post
// 然后读取form的in字段,就是input框的值显示出来
func FormServer(w http.ResponseWriter, req *http.Request) {
    w.Header().Set("Content-type", "text/html")
    switch req.Method {
        case "GET":
            io.WriteString(w, form)
        case "POST":
            io.WriteString(w, req.FormValue("in"))
    }
}

func LogPanic(f MyHandleFunc) MyHandleFunc {
    return func(w http.ResponseWriter, req *http.Request) {
        defer func() {
            if x := recover(); x != nil {
                log.Printf("[%v] caught panic: %v", req.RemoteAddr, x)
            }
        }()
        f(w, req)
    }
}

func main() {
        http.HandleFunc("/simple1", LogPanic(SimpleServer))
        http.HandleFunc("/simple2", LogPanic(FormServer))
        if err := http.ListenAndServe(":8081", nil) ; err != nil {
            panic(err)
        }
}

相关文章

  • 第15章 15.5-健壮的http应用

  • http的应用

    [TOC] 1. httpd-2.4 新特性: (1) MPM -支持-> DSO, 模块形式按需加载 (2) 支...

  • 深入浅出gRPC

    一、gRPC介绍 gRPC 是在 HTTP/2 之上实现的 RPC 框架,HTTP/2 是第 7 层(应用层)协议...

  • grpc客户端原理

    gRPC 是在 HTTP/2 之上实现的 RPC 框架,HTTP/2 是第 7 层(应用层)协议,它运行在 TCP...

  • HTTP协议摘要

    HTTP协议摘要 HTTP协议工作在第几层,它下层使用了哪些协议? HTTP是应用层协议,工作在第5层(TCP/I...

  • 健壮

    早上开源上学,在出门的时候,我怕他穿的少早晨凉。 开源:今天多少度? 我:26度 开源:没事,24度的时候我穿这件...

  • 2018-09-08第十五天课

    HTTP 监听客户端的请求 (地址和端口),默认端口是80静态HTTP 服务器koa 框架更小,更精简,更健壮的框...

  • OkHttp3使用教程

    OkHttp是Square出的Http通讯库,支持HTTP和HTTP/2,用于Android应用和Java应用。 ...

  • $http服务应用

    $http服务的使用场景: then()函数:可以用来处理$http服务的回调,then()函数接受两个可选的函数...

  • HTTP 笔记

    http 协议应用在应用层 应用层为应用乳尖提供了很多服务 http 发展历史第一个版本 Http/0.9 版本 ...

网友评论

      本文标题:第15章 15.5-健壮的http应用

      本文链接:https://www.haomeiwen.com/subject/qmjrthtx.html