推荐一个简化搜索的web小工具“咸鱼SOS”【附上服务器端代码】

咸鱼SOS 链接地址:http://xianyusos.fun

反正不要钱,不用白不用~ —— 周树人

使用咸鱼SOS可以简化搜索步骤,举个栗子,老师要小明同学在github中搜索“golang”关键字,查看golang的开源项目

  1. 普通小明会在浏览器的输入框中输入“github.com”,等网页显示出来后再找到搜索框搜索;

  2. 2B小明会先打开百度,在百度中搜索“github”,再选中github官网,等网页显示出来后再找到搜索框搜索;

  3. 文艺小明会把咸鱼SOS设置为首页或者加入书签,只用选中左边的GitHub,就可以直接使用中央的搜索框搜索github里的内容了。

服务端代码如下,请斧正: server.go

package main

import (
    "github.com/labstack/echo"
    "xianyusos/handlers"
    "io"
    "html/template"
    "time"
    "gopkg.in/redis.v5"
    "github.com/sirupsen/logrus"
    "os"
    "fmt"
)

const (
    PERIOD = 1*time.Hour
)

type Template struct {
    Templates *template.Template
}

func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
    return t.Templates.ExecuteTemplate(w, name, data)
}

func main() {
    if err := getEnvs(); err != nil {
        panic(err)
    }
    e := echo.New()
    defer e.Close()
    h, err := handlers.New()
    if err != nil {
        panic(err)
    }
    defer h.Client.Close()
    e.Renderer = &Template{
        Templates: template.Must(template.ParseGlob("views/*.html")),
    }
    logrus.SetOutput(os.Stdout)

    go func() {
        for {
            time.Sleep(PERIOD)
            if err := h.Client.Ping().Err(); err != nil {
                logrus.Errorf("Error in h.Client.Ping: [%s].", err.Error())
                h.Client = redis.NewClient(&redis.Options{
                    Addr: handlers.REDIS_ADDRESS,
                    Password: handlers.REDIS_PASSWORD,
                    MaxRetries: 5,
                })
                logrus.Infof("Reconnect redis[%s].", handlers.REDIS_ADDRESS)
            }
            for k, v := range h.VisitorsIp {
                if err := h.Client.HSet("visitors", k, v).Err(); err != nil {
                    logrus.Errorf("Error in h.Client.Set: [%s].", err.Error())
                    continue
                }
            }
            logrus.Info("Update the value of visitors success.")
        }
    }()

    e.GET("/", h.Home)
    e.GET("/:routerName", h.Search)
    e.Static("/static", "views")
    e.File("/favicon.ico", "views/katongxianyu.png")
    //h.RouterName["163music"] = true
    h.RouterName["github"] = true
    h.RouterName["baidu"] = true
    h.RouterName["bilibili"] = true
    h.RouterName["iqiyi"] = true
    h.RouterName["jd"] = true
    h.RouterName["mooc"] = true
    h.RouterName["qidian"] = true
    h.RouterName["runoob"] = true
    h.RouterName["segmentfault"] = true
    h.RouterName["stackoverflow"] = true
    h.RouterName["taobao"] = true
    h.RouterName["weibo"] = true
    h.RouterName["youku"] = true
    h.RouterName["zhihu"] = true
    e.Start(":8823")
}

func getEnvs() error {
    handlers.REDIS_ADDRESS = os.Getenv("REDIS_ADDRESS")
    if len(handlers.REDIS_ADDRESS) == 0 {
        return fmt.Errorf("Env [REDIS_ADDRESS] is nil.")
    }
    handlers.REDIS_PASSWORD = os.Getenv("REDIS_PASSWORD")
    if len(handlers.REDIS_PASSWORD) == 0 {
        return fmt.Errorf("Env [REDIS_PASSWORD] is nil.")
    }
    return nil
}

handler.go

package handlers

import (
    "github.com/labstack/echo"
    "net/http"
    "gopkg.in/redis.v5"
    "sync"
    "strings"
)

var (
    REDIS_ADDRESS = "na.huanyu0w0.cn:2333"
    REDIS_PASSWORD = "3.1415926"
)

type (
    handler struct {
        Client *redis.Client
        Mux sync.Mutex
        RouterName map[string]bool
        VisitorsIp map[string]string
    }
)

func New() (*handler, error) {
    h := new(handler)
    h.Client = redis.NewClient(&redis.Options{
        Addr: REDIS_ADDRESS,
        Password: REDIS_PASSWORD,
        MaxRetries: 5,
    })
    var err error
    h.VisitorsIp, err = h.Client.HGetAll("visitors").Result()
    if err != nil {
        return nil, err
    }
    h.Mux = sync.Mutex{}
    h.RouterName = make(map[string]bool)
    return h, nil
}

func (h *handler) Home(c echo.Context) error {
    routerName := ""
    for routerName = range h.RouterName {
        break
    }
    return c.Redirect(http.StatusFound, "/"+routerName)
}

func (h *handler) Search(c echo.Context) error {
    h.Mux.Lock()
    ip := strings.Split(c.Request().RemoteAddr, ":")[0]
    h.VisitorsIp[ip] = ip
    h.Mux.Unlock()
    routerName := c.Param("routerName")
    if len(routerName) == 0 {
        return echo.ErrNotFound
    }
    if b, ok := h.RouterName[routerName]; !ok && b == true {
        return echo.ErrNotFound
    }
    return c.Render(http.StatusOK, routerName, len(h.VisitorsIp))
}

1 个评论

谢谢大佬

要回复文章请先登录注册