如何在Go中编写简单的自定义http服务器? [英] How to write a simple custom http server in Go?

查看:1143
本文介绍了如何在Go中编写简单的自定义http服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Go的新手,试图编写自定义http server.Getting编译错误。如何在我的代码中实现ServeHTTP方法?

I am new to Go and trying to write a custom http server.Getting compilation error. How can I implement the ServeHTTP method in my code?

我的代码:

My Code:

package main

import (
        "net/http"
        "fmt"
        "io"
        "time"
    )


func myHandler(w http.ResponseWriter, req *http.Request){
    io.WriteString(w, "hello, world!\n")
}


func main() {

    //Custom http server
    s := &http.Server{
        Addr:           ":8080",
        Handler:        myHandler,
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 << 20,
    }

    err := s.ListenAndServe()
    if err != nil {
        fmt.Printf("Server failed: ", err.Error())
    }
}

编译时出错:

.\hello.go:21: cannot use myHandler (type func(http.ResponseWriter, *http.Request)) as type http.Handler in field value:
    func(http.ResponseWriter, *http.Request) does not implement http.Handler (missing ServeHTTP method)


推荐答案

您可以使用一个struct并定义 ServeHTTP HandlerFunc

You either use a struct and define ServeHTTP on it or simply wrap your function in a HandlerFunc

s := &http.Server{
    Addr:           ":8080",
    Handler:        http.HandlerFunc(myHandler),
    ReadTimeout:    10 * time.Second,
    WriteTimeout:   10 * time.Second,
    MaxHeaderBytes: 1 << 20,
}

这篇关于如何在Go中编写简单的自定义http服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆