Golang实现简易时间服务

Golang实现简易时间服务 最近我需要一个可通过 HTTP GET 请求访问的小型时间服务,于是编写了一个。它返回一个包含几种格式的 UTC 时间的 JSON。或许对其他人也有帮助。

GitHub GitHub

头像

geosoft1/time

Go 语言编写的时间服务。通过在 GitHub 上创建账户来为 geosoft1/time 的开发做出贡献。

希望你喜欢。


更多关于Golang实现简易时间服务的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang实现简易时间服务的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


这是一个很实用的Go语言时间服务实现。我来分析一下代码并提供一些技术细节:

package main

import (
    "encoding/json"
    "log"
    "net/http"
    "time"
)

type TimeResponse struct {
    Unix    int64  `json:"unix"`
    UTC     string `json:"utc"`
    ISO8601 string `json:"iso8601"`
    RFC3339 string `json:"rfc3339"`
}

func timeHandler(w http.ResponseWriter, r *http.Request) {
    now := time.Now().UTC()
    
    response := TimeResponse{
        Unix:    now.Unix(),
        UTC:     now.Format(time.RFC1123),
        ISO8601: now.Format("2006-01-02T15:04:05Z"),
        RFC3339: now.Format(time.RFC3339),
    }
    
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(response)
}

func main() {
    http.HandleFunc("/time", timeHandler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

这个实现有几个优点:

  1. 结构清晰:使用TimeResponse结构体定义JSON响应格式

  2. 时间格式化:提供了多种标准时间格式:

    • Unix时间戳(秒级)
    • RFC1123格式(HTTP标准)
    • ISO8601格式
    • RFC3339格式
  3. 性能优化:使用json.NewEncoder().Encode()直接流式输出到响应,比先编码到内存再写入更高效

如果需要添加功能,可以考虑:

// 添加时区支持
func timeHandler(w http.ResponseWriter, r *http.Request) {
    tz := r.URL.Query().Get("tz")
    var loc *time.Location
    var err error
    
    if tz != "" {
        loc, err = time.LoadLocation(tz)
        if err != nil {
            http.Error(w, "Invalid timezone", http.StatusBadRequest)
            return
        }
    } else {
        loc = time.UTC
    }
    
    now := time.Now().In(loc)
    // ... 其余代码
}

// 添加健康检查端点
func healthHandler(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("OK"))
}

这个时间服务简洁实用,适合作为微服务架构中的基础服务组件。

回到顶部