github.com/kelleygo/clashcore@v1.0.2/hub/route/upgrade.go (about)

     1  package route
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"net/http"
     7  	"os"
     8  
     9  	"github.com/kelleygo/clashcore/config"
    10  	"github.com/kelleygo/clashcore/hub/updater"
    11  	"github.com/kelleygo/clashcore/log"
    12  
    13  	"github.com/go-chi/chi/v5"
    14  	"github.com/go-chi/render"
    15  )
    16  
    17  func upgradeRouter() http.Handler {
    18  	r := chi.NewRouter()
    19  	r.Post("/", upgradeCore)
    20  	r.Post("/ui", updateUI)
    21  	return r
    22  }
    23  
    24  func upgradeCore(w http.ResponseWriter, r *http.Request) {
    25  	// modify from https://github.com/AdguardTeam/AdGuardHome/blob/595484e0b3fb4c457f9bb727a6b94faa78a66c5f/internal/home/controlupdate.go#L108
    26  	log.Infoln("start update")
    27  	execPath, err := os.Executable()
    28  	if err != nil {
    29  		render.Status(r, http.StatusInternalServerError)
    30  		render.JSON(w, r, newError(fmt.Sprintf("getting path: %s", err)))
    31  		return
    32  	}
    33  
    34  	err = updater.Update(execPath)
    35  	if err != nil {
    36  		log.Warnln("%s", err)
    37  		render.Status(r, http.StatusInternalServerError)
    38  		render.JSON(w, r, newError(fmt.Sprintf("%s", err)))
    39  		return
    40  	}
    41  
    42  	render.JSON(w, r, render.M{"status": "ok"})
    43  	if f, ok := w.(http.Flusher); ok {
    44  		f.Flush()
    45  	}
    46  
    47  	go restartExecutable(execPath)
    48  }
    49  
    50  func updateUI(w http.ResponseWriter, r *http.Request) {
    51  	err := config.UpdateUI()
    52  	if err != nil {
    53  		if errors.Is(err, config.ErrIncompleteConf) {
    54  			log.Warnln("%s", err)
    55  			render.Status(r, http.StatusNotImplemented)
    56  			render.JSON(w, r, newError(fmt.Sprintf("%s", err)))
    57  		} else {
    58  			log.Warnln("%s", err)
    59  			render.Status(r, http.StatusInternalServerError)
    60  			render.JSON(w, r, newError(fmt.Sprintf("%s", err)))
    61  		}
    62  		return
    63  	}
    64  
    65  	render.JSON(w, r, render.M{"status": "ok"})
    66  	if f, ok := w.(http.Flusher); ok {
    67  		f.Flush()
    68  	}
    69  }