侧边栏壁纸
博主头像
nivnek博主等级

道阻且长,行则将至

  • 累计撰写 21 篇文章
  • 累计创建 27 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

Simple go code example for output the http request header

kenvin
2023-10-11 / 0 评论 / 0 点赞 / 386 阅读 / 1723 字

Here’s a basic example of how you could write an HTTP server in Go (Golang) and print the HTTP request headers:

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    // Print all request headers
    for name, headers := range r.Header {
        for _, h := range headers {
            fmt.Fprintf(w, "%v: %v\n", name, h)
        }
    }
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

This will start an HTTP server on port 8080 of your machine. Whenever you make an HTTP request to http://localhost:8080, it will print all the incoming HTTP request headers.

This server doesn’t do much except print headers but it gives you a starting point. From here, you could add more routes, more complex request handling, etc.

You can run this code file using go run command as follows:

go run server.go

Please ensure Go is properly installed and configured on your machine to run this code. You can install it from the official website https://golang.org/dl/ if not already installed.

0

评论区