Golang에서 기본 macOS 응용 프로그램을 만들고 반응하는 방법완전한 코드 보호가 있는 js-1부분

소개


'어떻게'시리즈의 다음 문장을 읽는 것을 환영합니다!이번에는 Apple macOS를 위해 이 데스크톱 프로그램을 만드는 과정을 분석하고 Golang 코드를 작성하여 반응할 것입니다.js, 복제 보호가 있습니다.
우리는 마법이 없는 상황에서 이 점을 시도할 것이다!😉

문장 부분


Part 1: Third-party Go package manager
🕓 제2부분: 새로운 바둑 방식과 바둑 모듈

From author: this article (originally) was written about half-year ago, therefore I use dep package manager for Go. I'm preparing Part 2 of this article for modern coding with Go Modules.


본 조항의 목적

  • Golang에서 macOS를 위한 데스크톱 응용 프로그램을 만드는 가장 간단한 방법 중 하나를 보여 줍니다.
  • 보호 응용 프로그램 코드가 제3자에 의해 수정되지 않는 옵션을 표시합니다(예를 들어 상업 발행 기간).
  • 작업 환경

  • 시작v1.12.5
  • 노드.jsv12.3.1
  • 운영 체제

  • 애플 macOS 10.14.5 Mojave(darwin/amd64
  • 패키지 및 종속성 관리자

  • depv0.5.3(Go)
  • npmv6.9.0(Node.js)
  • 사용된 패키지


    가다

  • net/http - 웹 서버를 만드는 데 사용되는 표준 패키지godoc
  • gobuffalo/packr - 필요한 모든 소스를 실행 가능한 바이너리 파일에 패키지로 패키지화(GitHub
  • zserge/webview - 기본 운영 체제 창에 내장된 브라우저가 있는 플랫폼 간 소프트웨어 패키지GitHub
  • 만들기

    노드회사 명

  • facebook/create-react-app-macOS 어플리케이션의 전면(GitHub
  • axios/axios - AJAX 요청을 보다 쉽게 작성하기 위해GitHub

  • 이론적 기초


    현재 발생하고 있는 일을 더욱 잘 이해하기 위해서, 나는 당신이 우리가 의존하고 사용할 소프트웨어 패키지의 업무를 검사하는 것을 건의합니다.

    네트워크/http


    HTTP 클라이언트와 서버에서 실행되는 패키지를 제공합니다.표준 Go 제공에 포함되며 별도의 설치 및 구성이 필요하지 않습니다.
    이것은 우리에게 매우 흥미롭다. 왜냐하면 그것은 이해하기 쉽고 좋은 문서와 기능이 있기 때문이다http.FileServer().
    자세한 내용은 official documentation 을 참조하십시오.

    http。파일 서버()


    이 기능은 웹 서버가 지정한 폴더와 모든 파일에 완전히 접근할 수 있도록 하는 것이 관건이다.즉, http.FileServer() 함수는 웹 서버의 지정한 주소 (루트) 에 폴더를 불러올 수 있도록 합니다.
    예를 들어, 루트 폴더./static/images/photos를 마운트하여 http://localhost:8000/photos 에서 사용할 수 있도록 합니다.
    http.Handle("/photos", http.FileServer("./static/images/photos"))
    

    고브팔로/파크


    대화 제목이 있는 패키지입니다.그는 우리가 필요한 모든 파일을 바이너리 파일로 포장하는 것을 허락했다.

    Please note: we are working with the packr v1 branch.


    다음과 같은 프로젝트 디렉토리 구조가 있다고 가정합니다.
    $ tree .
    
    .
    ├── main.go
    └── templates
        ├── admin
        │   └── index.html
        └── index.html
    
    파일./main.go에는 다음이 포함됩니다.
    package main
    
    import (
        "fmt"
        "log"
    
        "github.com/gobuffalo/packr"
    )
    
    func main() {
        // Folder with templates that are needed
        // to add to binary file
        box := packr.NewBox("./templates")
    
        // Search file inside folder
        s, err := box.FindString("amdin/index.html")
        if err != nil {
            log.Fatal(err)
        }
    
        fmt.Println(s)
    }
    
    이제 이 항목을 실행 가능한 바이너리 파일로 컴파일합시다.또한 packr 패키지는 ./templates 폴더의 모든 내용을 포장합니다.
    $ packr build ./main.go
    
    현재 사용 중인 운영 체제나 아키텍처 대신 운영 체제나 아키텍처에 바이너리 파일을 만들려면 다음과 같이 호출할 수 있습니다 packr.
    $ GOOS=linux GOARCH=amd64 packr build ./main.go
    

    zserge/webview


    현대 그래픽 인터페이스를 만드는 데 사용되는 마이크로 크로스플랫폼 웹 탐색 패키지입니다.

    Please note: the article describes how to work with v0.1.0.


    파일./main.go에는 다음이 포함됩니다.
    package main
    
    import "github.com/zserge/webview"
    
    func main() {
        // Open Google into a desktop webview window,
        // 1024x768 px, without resize
        webview.Open("Google", "https://google.com", 1024, 768, false)
    }
    

    프로젝트 구조


    $ tree .
    
    .
    ├── vendor
    ├── ui
    │   ├── build
    │   ├── node_modules
    │   ├── public
    │   ├── src
    │   ├── package-lock.json
    │   └── package.json
    ├── helloworld.app
    ├── Gopkg.lock
    ├── Gopkg.lock
    ├── Makefile
    └── main.go
    
    기본 파일 및 폴더에 대한 설명
  • vendor - dep로 설치된 모든 패키지가 여기에 저장됩니다
  • ui - React가 있는 폴더입니다.js 응용 프로그램(전단)
  • ui/build - 생성된 React App 운영 버전이 있는 폴더
  • ui/src - React 응용 프로그램 소스 코드가 포함된 폴더
  • ui/package.json - 종속성 파일npm
  • helloworld.app-macOS 어플리케이션(전용 폴더)
  • Gopkg.toml - 종속성 파일dep
  • Makefile - 애플리케이션 구축을 위한 스크립트 작성
  • main.go-Golang 애플리케이션 소스 코드(백엔드)
  • 코드 작성


    충분한 이론.그가 말한 바와 같이 조금도 과장하지 않고 말하자면, 우리 시대의 가장 위대한 프로그래머 중의 하나Linus Torvalds:

    Talk is cheap. Show me the code.

    Linus Torvalds


    이 건의에 따라 코드를 작성합시다.
    나는 모든 줄의 코드를 단독으로 분석하지 않을 것이다. 왜냐하면 나는 그것이 군더기이고 그 반대라고 생각하기 때문이다.모든 코드 명세서는 상세한 주석을 제공했다.

    "전체 코드" 예시를 찾습니까?


    문제 없어!👌 GitHub에서 특별히 만든 저장소:

    회사 명 / 예제 - go-react-macos-app-1


    예: native macOS app on Go(Golang) 및 React회사 명

    git clonemake만 있습니다.

    초보자 비망록/복사 붙여넣기 개발자

    Great, when there is a full code listing at the end of the article, right? You can immediately, without reading the text, copy all the program code and see its execution... At this point, I would like to appeal to all readers who do not want to spend time on theory:

    Do not mindlessly copy code from the Internet!

    This will not help you (in understanding the code and subject of the article), nor the author (in explaining/helping in the comments).


    애플리케이션 프런트엔드


    반응하다js는 기능이 강하지만 배우기 쉬운 자바스크립트 라이브러리로 사용자 인터페이스를 만드는 데 사용되며 우리가 응용 프로그램의 앞부분을 실현하는 데 매우 적합하다.

    Please note: For this article, we will not use anything but the standard React.js page.


    현대의 모든 것처럼, 우리는 React를 설치하는 것부터 시작한다.js와 필요한 모든 보조 라이브러리.
  • 응용 프로그램에 폴더를 만들고 들어갑니다.
  • 완료된 응용 프로그램의 구조에 따라 React를 설치합니다../ui 디렉토리의 js:
  • $ npx create-react-app ui
    
  • 폴더로 이동하여 모든 컨텐트가 올바른지 확인합니다.
  • $ cd ui && npm start && open http://localhost:3000
    
  • 서버 개발 중지(눌러 Ctrl+C 및 설치axios 라이브러리:
  • $ npm i --save axios
    
  • 네!👍 ./ui/src/App.js 파일의 소스 코드:
  • // Import React and React Hooks
    import React, { useState, useEffect } from "react";
    
    // Import axios
    import axios from "axios";
    
    // Import logo and CSS
    import logo from "./logo.svg";
    import "./App.css";
    
    function App() {
      // Define storage for data
      const [state, setState] = useState([]);
    
      // Retrieving data from an AJAX request.
      // Remember that the function passed to useEffect will run,
      // after render is fixed on the screen.
      // See https://reactjs.org/docs/hooks-reference.html#useeffect
      useEffect(() => {
        axios
          .get("/hello") // GET request to URL /hello
          .then(resp => setState(resp.data)) // save response to state
          .catch(err => console.log(err)); // catch error
      });
    
      return (
        <div className="App">
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <p>Hello, {state.text}!</p>
            <a
              className="App-link"
              href="https://reactjs.org"
              target="_blank"
              rel="noopener noreferrer"
            >
              Learn React
            </a>
          </header>
        </div>
      );
    }
    
    export default App;
    

    애플리케이션 백엔드

  • 필요한 Go 패키지를 설치합니다.
  • $ dep ensure -add github.com/gobuffalo/packr
    $ dep ensure -add github.com/zserge/webview
    
  • 그 밖에 packr 유틸리티가 필요합니다. 이 유틸리티는 $GOPATH/bin/packr 콘솔에서 호출할 수 있습니다.
  • $ go get -u github.com/gobuffalo/packr/packr
    
  • ./main.go 파일의 소스 코드:
  • package main
    
    import (
        "encoding/json"
        "net/http"
    
        "github.com/gobuffalo/packr"
        "github.com/zserge/webview"
    )
    
    // Message : struct for message
    type Message struct {
        Text string `json:"text"`
    }
    
    func main() {
        // Bind folder path for packaging with Packr
        folder := packr.NewBox("./ui/build")
    
        // Handle to ./static/build folder on root path
        http.Handle("/", http.FileServer(folder))
    
        // Handle to showMessage func on /hello path
        http.HandleFunc("/hello", showMessage)
    
        // Run server at port 8000 as goroutine
        // for non-block working
        go http.ListenAndServe(":8000", nil)
    
        // Let's open window app with:
        //  - name: Golang App
        //  - address: http://localhost:8000
        //  - sizes: 800x600 px
        //  - resizable: true
        webview.Open("Golang App", "http://localhost:8000", 800, 600, true)
    }
    
    func showMessage(w http.ResponseWriter, r *http.Request) {
        // Create Message JSON data
        message := Message{"World"}
    
        // Return JSON encoding to output
        output, err := json.Marshal(message)
    
        // Catch error, if it happens
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
    
        // Set header Content-Type
        w.Header().Set("Content-Type", "application/json")
    
        // Write output
        w.Write(output)
    }
    

    기본 macOS 응용 프로그램 구축🏗

  • macOS 응용 프로그램의 디렉터리 구조를 만듭니다.
  • $ mkdir -p helloworld.app/Contents/MacOS
    
  • 컴파일./main.go 응용 프로그램 폴더:
  • $ go build -o helloworld.app/Contents/MacOS/helloworld
    
  • 어플리케이션 실행:
  • $ open helloworld.app
    
  • 결과:

  • Windows와 GNU/Linux의 상호 번역


    본고에서 제시한 이론 블록과 코드는 다른 운영체제를 위한 유사한 응용 프로그램 개발과 관련이 있다.이런 상황에서 코드는 변하지 않는다.

    Write the code once — run everywhere!


    이것은 크로스 시스템의 성질 때문이다.
  • GNU/Linux - 실행 가능한 바이너리 파일
  • Microsoft Windows - 실행 파일.exe
  • Apple macOS - 구조.app 내의 바이너리 파일
    우리는 아래의 문장에서 이것에 대해 연구를 진행할 것이다.

    Stay tuned, comment and write only good code!



    고정 재료


    이 글은 여기서 끝냅니다.지금 너는 8분 전보다 훨씬 많이 알고 있다.
    내 축하 받아!🎉
    10-15분간 분리하여 읽은 텍스트를 메모리로 복구하고 글에서 코드를 학습합니다.다음은 재료를 더욱 공고히 하기 위해 질문에 대답하고 연습을 해 보자.
    네, 물어봐도 돼요. 하지만 전제 조건은 기억이 안 나요.

    문제

  • 폴더를 지정된 주소(루트)에 불러오는 데 사용되는 표준 go 패키지net/http의 기능은 무엇입니까?
  • 표준 Go 패키지encoding/json의 봉인 함수는 무엇입니까?
  • 풀 HD 어플리케이션의 소스 코드에서 변경해야 하는 매개변수는 무엇입니까?
  • 없는 웹 서버를 시작하려면?
  • 명령은 무엇입니까?

    연습

  • goroutine 함수(packr build ./main.go로 테스트를 작성합니다.
  • 프런트엔드 어플리케이션에 대한 쓰기 테스트showMessage().
  • axios 라이브러리를 사용하지 않은 상태에서 AJAX가 요청한 코드를 다시 씁니다(전단 응용 프로그램에서).팁: 이 기능을 사용합니다Fetch API.
  • 함수의 프런트엔드 출력에 JSON 데이터를 추가합니다.예: 메시지 구조에 새 속성인 이모지를 추가하고 텍스트 속성을 출력합니다.
  • 응용 프로그램의 외관을 개선하려고 시도합니다.팁: 재료 UI를 사용하여 어셈블리 라이브러리를 시각화합니다(GitHub.
  • 포토 맨


    [제목] Jantine Doornboshttps://unsplash.com/photos/HvYy5SEefC8
    [1] 말https://unsplash.com/photos/WiONHd_zYI4
    [2] 페변 그로스https://unsplash.com/photos/XMFZqrGyV-Q
    [3] 프리실라 두프리즈https://unsplash.com/photos/XkKCui44iM0
    [프레젠테이션] 빅 쇼스타크 (글쓴이)

    붓을 대다.


    만약 당신이 이 블로그에 이런 글을 더 많이 발표하고 싶다면, 아래에 논평을 발표하고 구독해 주십시오.감사합니다.😘
    물론, 너는 LiberaPay 기부금으로 나를 지지할 수 있다.모든 기부금은 새로운 글을 작성하고 지역 사회를 위한 비영리 개원 프로젝트에 쓰일 것이다.

    좋은 웹페이지 즐겨찾기